var camear_variable = {
    canvas1 : document.getElementById("myCanvas1"),
    canvas2 : document.getElementById("myCanvas2"),
    canvas3 : document.getElementById("myCanvas3"),
    bgCanvas : document.getElementById('bgCanvas'),
    ctx : document.getElementById("myCanvas1").getContext("2d"),
    ctx2 : document.getElementById("myCanvas2").getContext("2d"),
    scaleFactor : document.getElementById("myCanvas1").width / parseInt(document.getElementById("myCanvas1").width),
    viewableArea : parseInt(document.getElementById("myCanvas1").width) * document.getElementById("myCanvas1").width / parseInt(document.getElementById("myCanvas1").width),
    touches : [],
    relativeMouse: '',
    currentSelection: '',
    canTouch : true,
    mouseDown : false,
    image1 : new Image(),
    touch : {
        touch1PosX: 0,
        touch1PosY: 0,
        touch2PosX: 0,
        touch2PosY: 0,
        initAngle: 0,
        angle: 0,
        angleChange: 0,
        initLength: 0,
        length: 0,
        fingerLength: 0,
        lengthChange: 0
    }
};

var camear = {
    fileChange: function (e) {
        var _this = this;
        var orientation,
            file = e.files[0],
            reader = new FileReader(),
            _fileNamelength = e.value.lastIndexOf('.'),
            _fileName = e.value.substr(_fileNamelength + 1);

        if (_fileName) {
            if (_fileName.toLowerCase() !== 'jpg' && _fileName.toLowerCase() !== 'jpeg' && _fileName.toLowerCase() !== 'png' && _fileName.toLowerCase() !== 'gif'&& _fileName.toLowerCase() !== 'bmp') {
                $(e)[0].value = ""; //修复重复选择bug
                var msg = "提交的照片格式错误，系统接受的文件格式有：jpg、jpeg、png、gif、bmp";
                alert(msg);
                return;
            }
        }

        _this.listener();

        if(file){
            camear_variable.canvas3.style.display = 'block';

            //获取照片方向角属性，用户旋转控制
            EXIF.getData(file, function() {
                EXIF.getAllTags(this);
                orientation = EXIF.getTag(this, 'Orientation');
                console.log(orientation);
                return;
            });

            reader.onload = function (e) {
                _this.getImgData(this.result, orientation, function (data) {
                    camear_variable.canvas3.style.display = 'none';
                    _this.compressImg(data, 750);

                    //选取图片成功后回调
                    try {
                        if (typeof(eval(camearCallback)) == "function") {
                            camearCallback();
                        }
                    } catch(e) {}
                });
            }
            reader.readAsDataURL(file);
        }
    },

    listener: function(parameter) {
        var _this = this;

        camear_variable.bgCanvas.addEventListener("touchstart", function (event) {
            _this.pointerStart(event);
        }, false);
        camear_variable.bgCanvas.addEventListener("touchmove", function (event) {
            _this.pointerMove(event);
        }, false);
        camear_variable.bgCanvas.addEventListener("touchend", function (event) {
            _this.pointerEnd(event);
        }, false);
        camear_variable.bgCanvas.addEventListener("touchcancel", function (event) {
            _this.pointerEnd(event);
        }, false);

        camear_variable.canvas1.addEventListener("touchstart", function (event) {
            _this.pointerStart(event);
        });
        camear_variable.canvas1.addEventListener("touchmove", function (event) {
            _this.pointerMove(event);
        });
        camear_variable.canvas1.addEventListener("touchend", function (event) {
            _this.pointerEnd(event);
        });
        camear_variable.canvas1.addEventListener("touchcancel", function (event) {
            _this.pointerEnd(event);
        });
    },

    getImgData: function (img, dir, next) {
        var _this = this;

        var image = new Image();
        image.onload = function () {
            var degree = 0, drawWidth, drawHeight, width, height;
            drawWidth = this.naturalWidth;
            drawHeight = this.naturalHeight;
            //以下改变一下图片大小
            var maxSide = Math.max(drawWidth, drawHeight);
            if (maxSide > 1024) {
                var minSide = Math.min(drawWidth, drawHeight);
                minSide = minSide / maxSide * 1024;
                maxSide = 1024;
                if (drawWidth > drawHeight) {
                    drawWidth = maxSide;
                    drawHeight = minSide;
                } else {
                    drawWidth = minSide;
                    drawHeight = maxSide;
                }
            }
            camear_variable.canvas3.width = width = drawWidth;
            camear_variable.canvas3.height = height = drawHeight;
            var context = camear_variable.canvas3.getContext('2d');
            //判断图片方向，重置canvas3大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
            switch (dir) {
                //iphone横屏拍摄，此时home键在左侧
                case 3:
                    degree = 180;
                    drawWidth = -width;
                    drawHeight = -height;
                    break;
                //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
                case 6:
                    camear_variable.canvas3.width = height;
                    camear_variable.canvas3.height = width;
                    degree = 90;
                    drawWidth = width;
                    drawHeight = -height;
                    break;
                //iphone竖屏拍摄，此时home键在上方
                case 8:
                    camear_variable.canvas3.width = height;
                    camear_variable.canvas3.height = width;
                    degree = 270;
                    drawWidth = -width;
                    drawHeight = height;
                    break;
            }
            //使用canvas3旋转校正
            context.rotate(degree * Math.PI / 180);
            context.drawImage(this, 0, 0, drawWidth, drawHeight);
            //返回校正图片
            next(camear_variable.canvas3.toDataURL("image/jpeg", 1));
        }
        image.src = img;
    },

    compressImg: function (imgData, maxWidth) {
        var _this = this;

        if (!imgData) return;
        camear_variable.image1.onload = function () {
            camear_variable.image1.xPos = camear_variable.canvas1.width / 2;
            camear_variable.image1.yPos = camear_variable.canvas1.height / 2;
            camear_variable.image1.initWidth = camear_variable.image1.width;
            camear_variable.image1.initHeight = camear_variable.image1.height;
            camear_variable.image1.currentWidth = _this.scale(camear_variable.image1.initHeight, camear_variable.viewableArea, camear_variable.image1.initWidth);
            camear_variable.image1.currentHeight = camear_variable.viewableArea;
            //console.log(camear_variable.image1.initWidth+','+camear_variable.image1.currentHeight);
            if (camear_variable.image1.currentWidth < camear_variable.viewableArea) {
                camear_variable.image1.currentWidth = camear_variable.viewableArea;
                camear_variable.image1.currentHeight = _this.scale(camear_variable.image1.initWidth, camear_variable.viewableArea, camear_variable.image1.initHeight);
            }

            //image1宽高设置为改变后的宽高
            camear_variable.image1.initWidth = camear_variable.image1.currentWidth;
            camear_variable.image1.initHeight = camear_variable.image1.currentHeight;

            //console.log(image1.currentWidth+','+image1.currentHeight);
            camear_variable.image1.initAngle = 0;
            camear_variable.image1.angle = 0;
            _this.update(camear_variable.image1);
        };
        camear_variable.image1.src = imgData;
    },

    getCurrentSelection: function (position) {
        // if(position.clientX>image2.xPos && position.clientX<image2.xPos+image2.initWidth && position.clientY>image2.yPos && position.clientY-85<image2.yPos+image2.initHeight ){
        //     return image2;
        // }
        return camear_variable.image1;
    },

    scale: function (oldSize, newSize, other) {
        var _this = this;

        var scaleFactor = newSize / oldSize;
        return other * scaleFactor;
    },

    pointerStart: function (event) {
        var _this = this;

        if (!camear_variable.canTouch) return;
        camear_variable.currentSelection = _this.getCurrentSelection(event.touches[0]);
        var relativeTouch1;
        var relativeTouch2;

        // single touch
        if (event.touches !== undefined && event.touches.length === 1) {
            relativeTouch1 = _this.getRelative(event.touches[0]);
            //position
            camear_variable.touch.touch1PosX = relativeTouch1.x;
            camear_variable.touch.touch1PosY = relativeTouch1.y;
            camear_variable.touch.offsetX = camear_variable.touch.touch1PosX - camear_variable.currentSelection.xPos;
            camear_variable.touch.offsetY = camear_variable.touch.touch1PosY - camear_variable.currentSelection.yPos;
        }
        // multi touch
        else if (event.touches !== undefined && event.touches.length > 1) {
            camear_variable.currentSelection.initAngle = camear_variable.currentSelection.angle;
            camear_variable.currentSelection.initWidth = camear_variable.currentSelection.currentWidth;
            camear_variable.currentSelection.initHeight = camear_variable.currentSelection.currentHeight;
            relativeTouch1 = _this.getRelative(event.touches[0]);
            relativeTouch2 = _this.getRelative(event.touches[1]);

            //position
            camear_variable.touch.touch1PosX = relativeTouch1.x;
            camear_variable.touch.touch1PosY = relativeTouch1.y;
            camear_variable.touch.touch2PosX = relativeTouch2.x;
            camear_variable.touch.touch2PosY = relativeTouch2.y;

            var mid = _this.findMidPoint(relativeTouch1, relativeTouch2);
            camear_variable.touch.offsetX = mid.x - camear_variable.currentSelection.xPos;
            camear_variable.touch.offsetY = mid.y - camear_variable.currentSelection.yPos;

            //angle
            camear_variable.touch.initAngle = _this.slopeAngle(relativeTouch1, relativeTouch2);
            camear_variable.touch.angle = _this.slopeAngle(relativeTouch1, relativeTouch2);
            camear_variable.touch.angleChange = 0;
            //length
            camear_variable.touch.initLength = _this.findLength(relativeTouch1, relativeTouch2);
            camear_variable.touch.lengthChange = 0;
        }
    },

    pointerMove: function (event) {
        var _this = this;

        if (!camear_variable.canTouch) return;

        var relativeTouch1;
        var relativeTouch2;
        var Piw = camear_variable.canvas1.width/2;
        var movex = camear_variable.currentSelection.initWidth-camear_variable.canvas1.width;
        var movey =  camear_variable.currentSelection.initHeight-camear_variable.canvas1.height;

        event.preventDefault();
        camear_variable.touches = event.touches;
        //单点触摸
        if (event.touches !== undefined && event.touches.length === 1) {
            relativeTouch1 = _this.getRelative(event.touches[0]);
            //position
            camear_variable.touch.touch1PosX = relativeTouch1.x;
            camear_variable.touch.touch1PosY = relativeTouch1.y;
            relativeTouch1 = {
                x: camear_variable.touch.touch1PosX - camear_variable.touch.offsetX,
                y: camear_variable.touch.touch1PosY - camear_variable.touch.offsetY
            };

            //限制x轴拖动范围
            if(relativeTouch1.x>=Piw+movex/2){
                relativeTouch1.x = Piw+movex/2;
            }
            if(relativeTouch1.x<=Piw-movex/2){
                relativeTouch1.x = Piw-movex/2;
            }

            //限制y轴拖动范围
            if(relativeTouch1.y<=Piw-movey/2){
                relativeTouch1.y = Piw-movey/2;
            }
            if(relativeTouch1.y>=Piw+movey/2){
                relativeTouch1.y =Piw+movey/2;
            }

            // console.log(relativeTouch1,camear_variable.image1.currentHeight);
            _this.moveImage(camear_variable.currentSelection, relativeTouch1);
        }
        //多点触摸
        if (event.touches !== undefined && event.touches.length > 1) {

            relativeTouch1 = _this.getRelative(event.touches[0]);
            relativeTouch2 = _this.getRelative(event.touches[1]);
            //position
            camear_variable.touch.touch1PosX = relativeTouch1.x;
            camear_variable.touch.touch1PosY = relativeTouch1.y;
            camear_variable.touch.touch2PosX = relativeTouch2.x;
            camear_variable.touch.touch2PosY = relativeTouch2.y;
            //angle
            camear_variable.touch.angle = _this.slopeAngle(relativeTouch1, relativeTouch2);
            camear_variable.touch.angleChange = camear_variable.touch.angle - camear_variable.touch.initAngle;

            //length
            camear_variable.touch.length = _this.findLength(relativeTouch1, relativeTouch2);
            camear_variable.touch.lengthChange = camear_variable.touch.length - camear_variable.touch.initLength;

            relativeTouch1 = {
                x: camear_variable.touch.touch1PosX,
                y: camear_variable.touch.touch1PosY
            };
            relativeTouch2 = {
                x: camear_variable.touch.touch2PosX,
                y: camear_variable.touch.touch2PosY
            };

            var mid = _this.findMidPoint(relativeTouch1, relativeTouch2);

            // 控制旋转操作
            // _this.twoFingerRotate(camear_variable.currentSelection, mid);
            _this.twoFingerResize(camear_variable.currentSelection, mid);

            //多点触摸移动位置
            // mid.x -= camear_variable.touch.offsetX;
            // mid.y -= camear_variable.touch.offsetY;
            // _this.moveImage(camear_variable.currentSelection, mid)
        }

        // Mouse
        if (camear_variable.mouseDown) {
            camear_variable.relativeMouse = {
                x: camear_variable.touch.touch1PosX - camear_variable.touch.offsetX,
                y: camear_variable.touch.touch1PosY - camear_variable.touch.offsetY
            };
            console.log(camear_variable.relativeMouse);
            _this.moveImage(camear_variable.currentSelection, camear_variable.relativeMouse);
        }
        _this.update(camear_variable.currentSelection);
    },

    pointerEnd: function (event) {
        var _this = this;

        if (!camear_variable.canTouch) return;

        camear_variable.currentSelection.initAngle = camear_variable.currentSelection.angle;
        camear_variable.currentSelection.initWidth = camear_variable.currentSelection.currentWidth;
        camear_variable.currentSelection.initHeight = camear_variable.currentSelection.currentHeight;

        camear_variable.touch.angle = 0;
        camear_variable.touch.angleChange = 0;

        camear_variable.touch.length = 0;
        camear_variable.touch.lengthChange = 0;

        if (event !== undefined) {
            if (event.touches !== undefined && event.touches.length == 1) {
                relativeTouch1 = _this.getRelative(event.touches[0]);
                camear_variable.touch.touch1PosX = relativeTouch1.x;
                camear_variable.touch.touch1PosY = relativeTouch1.y;
                camear_variable.touch.offsetX = camear_variable.touch.touch1PosX - camear_variable.currentSelection.xPos;
                camear_variable.touch.offsetY = camear_variable.touch.touch1PosY - camear_variable.currentSelection.yPos;
            }
        }
    },

    moveImage: function (image, location) {
        var _this = this;

        if (_this.isInsideImage(image, location)) {
            image.xPos = location.x;
            image.yPos = location.y;
        }
    },

    getRelative: function (position) {
        var _this = this;

        return {//放大缩小倍数
            x: _this.makeRelative(position).x * 3,
            y: _this.makeRelative(position).y * 3
        };
    },

    makeRelative: function (object) {
        var _this = this;

        var relativeCoords;

        if (typeof object.clientX !== "undefined") {
            relativeCoords = {
                x: (object.clientX - camear_variable.canvas1.getBoundingClientRect().left) * camear_variable.scaleFactor,
                y: (object.clientY - camear_variable.canvas1.getBoundingClientRect().top) * camear_variable.scaleFactor
            };
        } else {
            relativeCoords = {
                x: (object.x - camear_variable.canvas1.getBoundingClientRect().left) * camear_variable.scaleFactor,
                y: (object.y - camear_variable.canvas1.getBoundingClientRect().top) * camear_variable.scaleFactor
            };
        }
        return relativeCoords;
    },

    isInsideImage: function (image, pointer) {
        var _this = this;

        return _this.isInside(image.xPos - image.currentWidth / 2, image.yPos - image.currentHeight / 2, image.currentWidth, image.currentHeight, pointer.x, pointer.y);
    },

    isInside: function (x1, y1, width1, height1, x2, y2) {
        var _this = this;

        return x2 >= x1 &&
            x2 < x1 + width1 &&
            y2 >= y1 &&
            y2 < y1 + height1;
    },

    drawRotatedImage: function (image) {
        var _this = this;

        camear_variable.ctx2.save();
        camear_variable.ctx2.translate(camear_variable.image1.xPos, camear_variable.image1.yPos);
        camear_variable.ctx2.rotate(camear_variable.image1.angle);

        camear_variable.ctx2.translate(-camear_variable.image1.xPos, -camear_variable.image1.yPos);
        _this.drawImageIOSFix(camear_variable.ctx2, camear_variable.image1, 0, 0, camear_variable.image1.width, camear_variable.image1.height, (camear_variable.image1.xPos - (camear_variable.image1.currentWidth / 2)), (camear_variable.image1.yPos - (camear_variable.image1.currentHeight / 2)), camear_variable.image1.currentWidth, camear_variable.image1.currentHeight);
        camear_variable.ctx2.restore();
        if (image == camear_variable.image1) {
            camear_variable.ctx.save();
            camear_variable.ctx.translate(camear_variable.image1.xPos, camear_variable.image1.yPos);
            camear_variable.ctx.rotate(camear_variable.image1.angle);
            camear_variable.ctx.translate(-camear_variable.image1.xPos, -camear_variable.image1.yPos);
            _this.drawImageIOSFix(camear_variable.ctx, camear_variable.image1, 0, 0, camear_variable.image1.width, camear_variable.image1.height, (camear_variable.image1.xPos - (camear_variable.image1.currentWidth / 2)), (camear_variable.image1.yPos - (camear_variable.image1.currentHeight / 2)), camear_variable.image1.currentWidth, camear_variable.image1.currentHeight);
            camear_variable.ctx.restore();
        }

        camear_variable.ctx.save();
        camear_variable.ctx.translate(image.xPos, image.yPos);
        camear_variable.ctx.rotate(image.angle);
        camear_variable.ctx.translate(-image.xPos, -image.yPos);
        if (image == camear_variable.image1) {
            _this.drawImageIOSFix(camear_variable.ctx, image, 0, 0, image.width, image.height, (image.xPos - (image.currentWidth / 2)), (image.yPos - (image.currentHeight / 2)), image.currentWidth, image.currentHeight);
        } else {
            camear_variable.ctx.drawImage(image, 0, 0, image.width, image.height, (image.xPos - (image.currentWidth / 2)), (image.yPos - (image.currentHeight / 2)), image.currentWidth, image.currentHeight);
        }

        camear_variable.ctx.restore();
    },


    findLength: function (start, end) {
        var _this = this;

        var a = end.x - start.x;
        var b = end.y - start.y;
        var csq = (a * a) + (b * b);
        return Math.floor(Math.sqrt(csq));
    },

    findMidPoint: function (start, end) {
        var _this = this;

        return {
            x: (start.x + end.x) / 2,
            y: (start.y + end.y) / 2
        };
    },

    slopeAngle: function (start, end) {
        var _this = this;

        var run = end.x - start.x;
        var rise = end.y - start.y;
        return Math.atan2(run, rise);
    },

    //放大缩小图片
    resizeImage: function (image, newWidth, newHeight) {
        var _this = this;

        var origWidth = image.currentWidth;
        var origHeight = image.currentHeight;

        if(origWidth>origHeight){
            //当宽大于高时 限制最小高度
            if (newHeight < camear_variable.canvas1.height) {
                newHeight = camear_variable.canvas1.height;
            } else {
                newHeight = newHeight;
            }
            image.currentWidth = (origWidth / origHeight) * newHeight;
            image.currentHeight = newHeight;
        }else {
            //当宽小于高时 限制最小宽度
            if (newWidth < camear_variable.canvas1.width) {
                newWidth = camear_variable.canvas1.width;
            } else {
                newWidth = newWidth;
            }
            image.currentWidth = newWidth;
            image.currentHeight = (origHeight / origWidth) * newWidth;
        }
    },

    twoFingerResize: function (image, location) {
        var _this = this;

        if (_this.isInsideImage(image, location)) {
            camear_variable.touch.lengthChange = camear_variable.touch.length - camear_variable.touch.initLength;
            _this.resizeImage(image, image.initWidth + camear_variable.touch.lengthChange, image.initHeight + camear_variable.touch.lengthChange);
        }
    },

    //旋转操作
    twoFingerRotate: function (image, location) {
        var _this = this;

        if (_this.isInsideImage(image, location)) {
            image.angle = image.initAngle - camear_variable.touch.angleChange;
        }
    },

    update: function (image) {
        var _this = this;

        camear_variable.ctx.clearRect(0, 0, camear_variable.canvas1.width, camear_variable.canvas1.height);
        _this.drawRotatedImage(image);
    },

    loadColorMatrix: function (matrix) {
        var _this = this;

        var imageData = camear_variable.ctx.getImageData(0, 0, camear_variable.canvas1.width, camear_variable.canvas1.height);
        camear_variable.ctx.putImageData(_this.colorMatrixFilter(imageData, matrix), 0, 0);
    },

    colorMatrixFilter: function (pixels, m) {
        var _this = this;

        var d = pixels.data;
        for (var i = 0; i < d.length; i += 4) {
            var r = d[i];
            var g = d[i + 1];
            var b = d[i + 2];
            var a = d[i + 3];

            d[i] = r * m[0] + g * m[1] + b * m[2] + a * m[3] + m[4];
            d[i + 1] = r * m[5] + g * m[6] + b * m[7] + a * m[8] + m[9];
            d[i + 2] = r * m[10] + g * m[11] + b * m[12] + a * m[13] + m[14];
            d[i + 3] = r * m[15] + g * m[16] + b * m[17] + a * m[18] + m[19];
        }
        return pixels;
    },


    /**
     * Detecting vertical squash in loaded image.
     * Fixes a bug which squash image vertically while drawing into canvas for some images.
     * This is a bug in iOS6 devices. This function from https://github.com/stomita/ios-imagefile-megapixel
     *
     */
    detectVerticalSquash: function (img) {
        var _this = this;

        var iw = img.naturalWidth, ih = img.naturalHeight;
        var canvas = document.createElement('canvas');
        canvas.width = 1;
        canvas.height = ih;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        var data = ctx.getImageData(0, 0, 1, ih).data;
        // search image edge pixel position in case it is squashed vertically.
        var sy = 0;
        var ey = ih;
        var py = ih;
        while (py > sy) {
            var alpha = data[(py - 1) * 4 + 3];
            if (alpha === 0) {
                ey = py;
            } else {
                sy = py;
            }
            py = (ey + sy) >> 1;
        }
        var ratio = (py / ih);
        return (ratio === 0) ? 1 : ratio;
    },

    /**
     * A replacement for context.drawImage
     * (args are for source and destination).
     */
    drawImageIOSFix: function (ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
        var _this = this;

        var vertSquashRatio = _this.detectVerticalSquash(img);

        ctx.drawImage(img, sx * vertSquashRatio, sy * vertSquashRatio,
            sw * vertSquashRatio, sh * vertSquashRatio,
            dx, dy, dw, dh);
    }
};
